﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using CLEX.Service.DataContracts;

namespace CLEX.Client.Metro.ViewModel.Home
{
    public class DatabaseNewVM : VMBase
    {
        private readonly IFacade facade;
        private readonly IPopupService popup;
        private readonly UserData user;
        private string connectionString;
        private string connectionStringErrors;
        private readonly RelayCommand create;
        private readonly RelayCommand cancel;

        public string ConnectionString
        {
            get { return connectionString; }
            set
            {
                if (connectionString != value)
                {
                    connectionString = value;
                    RaisePropertyChanged("ConnectionString");
                    create.RaiseCanExecuteChanged();
                }
            }
        }

        public string ConnectionStringErrors
        {
            get { return connectionStringErrors; }
            private set
            {
                if (connectionStringErrors != value)
                {
                    connectionStringErrors = value;
                    RaisePropertyChanged("ConnectionStringErrors");
                }
            }
        }

        public ICommand Create
        {
            get { return create; }
        }

        public ICommand Cancel
        {
            get { return cancel; }
        }

        public DatabaseNewVM(IFacade facade, IPopupService popup, UserData user)
        {
            this.facade = facade;
            this.popup = popup;
            this.user = user;
            this.create = new RelayCommand(DoCreate, CanCreate);
            this.cancel = new RelayCommand(DoCancel);
            this.create.CanExecuteChanged += Save_CanExecuteChanged;
        }

        private void Save_CanExecuteChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                ConnectionStringErrors = "Please enter a connection string.";
            }
            else
            {
                ConnectionStringErrors = null;
            }
        }

        private void DoCreate()
        {
            try
            {
                facade.CreateDatabase(user.UserId, connectionString);
            }
            catch (Exception ex)
            {
                facade.ShowUnexpectedError("The database could not be created.", ex.Message);
                return;
            }
            popup.ClosePopup();
        }

        private bool CanCreate()
        {
            return !string.IsNullOrWhiteSpace(connectionString);
        }

        private void DoCancel()
        {
            popup.ClosePopup();
        }
    }
}
